#include "chttpmanger.h"
#include "serversetting.h"
#include <QDebug>

CHttpManger::CHttpManger(QObject *parent) :
    QObject(parent)
{
    _try_times = 0;
    _request_ok = false;
    _manager = new QNetworkAccessManager(this);

    connect(_manager,SIGNAL(finished(QNetworkReply*)),  //关联信号和槽
                this,SLOT(replyFinished(QNetworkReply*)));
}

void CHttpManger::doGetProject()
{

    QString reqUrl = ServerSetting::defaultSetting()->_project_url;
    // http://192.168.1.137:8080/TTG_ic/rest/jsonServices/showAll?projectId=1

    QString req = QString("gateway_serial=%1&default_project=1")
            .arg(ServerSetting::defaultSetting()->_serial);

    httpPostSend(reqUrl,req.toUtf8());
}

void CHttpManger::httpPostSend(QString web_url, QByteArray post_data)
{
    _request_ok = false;
    QNetworkRequest network_request;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    //network_request.setHeader(QNetworkRequest::ContentLengthHeader, post_data.length());

    //设置url
    //network_request.setUrl(QUrl("http://121.42.8.158/ttg/sleep?a=0"));
    network_request.setUrl(QUrl(web_url));
    //发送请求
    _manager->post(network_request,post_data);
    //_manager->get(network_request+"?"+post_data);
}

void CHttpManger::httpGetSend(QString web_get_url)
{
    QNetworkRequest network_request;
    //设置头信息
    //network_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    //network_request.setHeader(QNetworkRequest::ContentLengthHeader, post_data.length());

    //设置url
    //network_request.setUrl(QUrl("http://121.42.8.158/ttg/sleep?a=0"));
    network_request.setUrl(QUrl(web_get_url));
    //发送请求

    _manager->get(network_request);
}

void CHttpManger::replyFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
        _request_ok = true;
    else
        _request_ok = false;

    QByteArray d = reply->readAll();
    reply->deleteLater();
    //qDebug() << "Http get reply: " << d;
    emit s_reply(d);
}
